package com.wuhuiyue.controller;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.db.nosql.redis.RedisDS;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuhuiyue.entity.Result;
import com.wuhuiyue.entity.User;
import com.wuhuiyue.service.IUserService;
import com.wuhuiyue.utils.JwtUtils;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hy-woo
 * @since 2022-06-14
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/getCode")
    public Result getCode(@RequestBody User user) throws Exception {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("tel",user.getTel());
        User u1 = userService.getOne(wrapper);
        if (u1==null){
            return Result.failed(201,"用户不存在");
        }
        String code = RandomUtil.randomInt(1000, 9999) + "";
        System.err.println("------ 验证码是 ---"+code);
        redisTemplate.opsForValue().set(user.getCodeKey(),code,1, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(user.getCodeKey()+"tel",u1.getTel(),1,TimeUnit.MINUTES);
        ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "111292", "\n" +
                "f7ab991d-1ae0-4d51-b9bf-8bf5716316bf");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", u1.getTel());
        params.put("templateId", "8771");
        String[] templateParams = new String[2];
        templateParams[0] = code;
        templateParams[1] = "5分钟";
        params.put("templateParams", templateParams);
        String result = client.send(params);
        return Result.OK();
    }

    @RequestMapping("/mylogin")
    public Result mylogin(@RequestBody User user){
        if (!user.getTel().equals((String) redisTemplate.opsForValue().get(user.getCodeKey()+"tel"))){
            return Result.failed(201,"手机号错误");
        }
        if (!user.getTelCode().equals((String) redisTemplate.opsForValue().get(user.getCodeKey()))){
            return Result.failed(202,"验证码错误");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("tel",user.getTel());
        User u1 = userService.getOne(wrapper);
        if (u1==null){
            return Result.failed(201,"用户不存在");
        }
        try {
            // 认证
            UsernamePasswordAuthenticationToken uptoken = new UsernamePasswordAuthenticationToken(u1.getUsername(), u1.getPassword());
            Authentication authenticate = authenticationManager.authenticate(uptoken);
            User ylogin = (User) authenticate.getPrincipal();
            String token = JwtUtils.createToken(ylogin.getUsername(), 30, JSONUtil.toJsonStr(ylogin));
            redisTemplate.opsForValue().set(ylogin.getUsername(),authenticate,30,TimeUnit.MINUTES);
            HashMap<String,Object> map=new HashMap<>();
            map.put("token",token);
            map.put("userInfo",ylogin);
            return Result.OK(map);
        }catch (Exception e){
            e.printStackTrace();
            System.err.println("-------"+e);
            return Result.failed(203,"报错");
        }
    }

    @RequestMapping("/userLogin")
    public Result userLogin(@RequestBody User user){
        try {
            // 认证
            UsernamePasswordAuthenticationToken uptoken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
            Authentication authenticate = authenticationManager.authenticate(uptoken);
            User ylogin = (User) authenticate.getPrincipal();
            String token = JwtUtils.createToken(ylogin.getUsername(), 30, JSONUtil.toJsonStr(ylogin));
            redisTemplate.opsForValue().set(ylogin.getUsername(),authenticate,30,TimeUnit.MINUTES);
            HashMap<String,Object> map=new HashMap<>();
            map.put("token",token);
            map.put("userInfo",ylogin);
            return Result.OK(map);
        }catch (Exception e){
            e.printStackTrace();
            System.err.println("-------"+e);
            return Result.failed(201,"报错");
        }
    }

}
